<?php
/**
 * Created by PhpStorm.
 * User: DD
 * Date: 2016/7/16
 * Time: 11:34
 */
use think\Log;

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function ccnn_md5($str, $key = 'ccnn')
{
    return '' === $str ? '' : md5(sha1($str) . $key);
}

function ccnn_is_valide_openid($openid)
{
    return !empty($openid) && strlen($openid) == 28;
}

function ccnn_is_weixin_request()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

function ccnn_is_ios_request()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false) {
        return true;
    }
    return false;
}

function ccnn_is_android_request()
{
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false) {
        return true;
    }
}

function ccnn_build_orderno()
{
    return 'D' . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

function ccnn_request_url()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    return "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}

function ccnn_request_host()
{
    return $_SERVER['HTTP_HOST'];
}

function ccnn_request_baseurl()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    return "$protocol$_SERVER[HTTP_HOST]";
}

function ccnn_options($modelname, $empty = 0)
{
    $rows = M($modelname)->getField('id,title');
    if ($empty > 0) {
        $rows['0'] = '(无)';
    }
    return json_encode($rows);
}

function ccnn_qoute($str)
{
    return str_replace('"', '\"', $str);
}

function ccnn_safe_array(array $arr, array $fields, array $exceptFields = [])
{
    $rt = [];
    foreach ($fields as $field) {
        if (in_array($field, $exceptFields)) {
            $rt[$field] = $arr[$field];
        } else {
            $rt[$field] = htmlspecialchars($arr[$field]);
        }
    }
    return $rt;
}

function ccnn_lrcutstring($str, $len = 5)
{
    if (mb_strlen($str) <= $len * 2) {
        return $str;
    }
    return mb_substr($str, 0, $len) . '...' . mb_substr($str, mb_strlen($str) - $len);
}

function ccnn_cutstring($str, $len, $subfix = '...')
{
    if (mb_strlen($str) <= $len) {
        return $str;
    }
    return mb_substr($str, 0, $len) . $subfix;
}

function ccnn_get_client_ip($type = 0)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos = array_search('unknown', $arr);
        if (false !== $pos) unset($arr[$pos]);
        $ip = trim($arr[0]);
    } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = ip2long($ip);
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function ccnn_showerror($message)
{
    $result = R('services/errorHandler/showError', ['message' => $message]);
    exit($result);
}

function ccnn_log($info, $type = 'error')
{
    Log::clear();
    Log::write($info, $type);
    Log::save();
}

function ccnn_ai(array $arr, $field, $default = '', $filterFunc = '')
{
    if (array_key_exists($field, $arr)) {
        $v = $arr[$field];
        if ($filterFunc && function_exists($filterFunc)) {
            $v = $filterFunc($v);
        }
        return $v;
    }
    return $default;
}

function ccnn_rand_float($min = 0, $max = 1)
{
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

;

function ccnn_syslog($content, $type = 'error')
{
    if (!is_string($content)) {
        $content = var_export($content, true);
    }
    M('system_log')->add([
        'level' => $type,
        'content' => $content,
        'create_time' => \app\common\util\DateTimeUtil::now()
    ]);
}

function ccnn_new_ip()
{
    static $ip;
    if (!empty($ip)) {
        return $ip;
    }
    $ip_long = array(
        array('607649792', '608174079'), //36.56.0.0-36.63.255.255
        array('1038614528', '1039007743'), //61.232.0.0-61.237.255.255
        array('1783627776', '1784676351'), //106.80.0.0-106.95.255.255
        array('2035023872', '2035154943'), //121.76.0.0-121.77.255.255
        array('2078801920', '2079064063'), //123.232.0.0-123.235.255.255
        array('-1950089216', '-1948778497'), //139.196.0.0-139.215.255.255
        array('-1425539072', '-1425014785'), //171.8.0.0-171.15.255.255
        array('-1236271104', '-1235419137'), //182.80.0.0-182.92.255.255
        array('-770113536', '-768606209'), //210.25.0.0-210.47.255.255
        array('-569376768', '-564133889'), //222.16.0.0-222.95.255.255
    );
    $rand_key = mt_rand(0, 9);
    $ip = long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
    return $ip;
}

function ccnn_redirect($url)
{
    header('Location:' . $url);
    exit;
}

function ccnn_sys_setting($key, $default = null)
{
    //key_code,key_value
    $value = \app\common\model\SysSetting::instance()->where(['key_code' => trim($key)])->getField('key_value');
    if (empty($value)) {
        return $default;
    }
    return $value;
}

function ccnn_dateformat($time, $format = 'y-m-d')
{
    if (!empty($time)) {
        if ($format == 'y-m-d') {
            return strstr(trim($time), ' ', true);
        } else if ($format == 'm-d') {
            return substr(strstr(strstr(trim($time), ' ', true), '-'), 1);
        }
    }
    return '';
}

function ccnn_dateformat2($time, $format = 'y-m-d')
{
    if (!empty($time)) {
        if ($format == 'y-m-d') {
            return date('Y年m月d日', strtotime($time));
        } else if ($format == 'm-d') {
            return substr(strstr(strstr(trim($time), ' ', true), '-'), 1);
        }
    }
    return '';
}

function ccnn_img($img, $size = '', $watermark = 0)
{
    return $img;
}


function _img_url($wh, $img = '')
{
    if (empty($img)) {
        if (empty($wh)) {
            return '/images/timg.jpg';
        }
        list($w, $h) = explode('x', $wh);
        if (!empty($w) && !empty($h)) {
            return U('services/img/placeholder', ['w' => $w, 'h' => $h]);
        }
    }
    return ccnn_img($img);
}

//
//function ccnn_url_prefix($prefix = null)
//{
//    static $_prefix = '';
//    if (is_null($prefix)) {
//        return $_prefix;
//    }
//    return $_prefix = $prefix;
//}

function ccnn_url($type, $param = '', $link = '/')
{
    return '/' . $type . $link . $param . '.html';
}

function ccnn_ext($file, $default = '')
{
    $ext = substr(strrchr($file, '.'), 1);
    if (!empty($ext)) {
        return $ext;
    }
    return $default;
}

function ccnn_size($size)
{
    if ($size < 1000) {
        return $size . 'M';
    }
    return round($size / 1000, 2) . 'G';
}

function _int2time($minutes)
{
    return str_pad(intval($minutes / 60), 2, '0', STR_PAD_LEFT) . ':' . str_pad($minutes % 60, 2, '0', STR_PAD_LEFT) . ':00';
}

function _m($name, $idValue, $default = '', $where = [])
{
    list($name, $field) = explode('.', $name);
    $rt = '';
    if (!empty($name) && !empty($field) && !empty($idValue)) {
        if (is_string($idValue)) {
            $idValue = explode(',', $idValue);
        } else {
            $idValue = [$idValue];
        }
        $where['id'] = ['in', $idValue];
        $arr = M($name)->where($where)->getField($field, true);
        if (!empty($arr)) {
            $rt = implode(',', $arr);
        }
    }
    if (empty($rt)) {
        $rt = $default;
    }
    return $rt;
}

function _logo($default = '')
{
    return '';
}

function _rand_str($length = 15)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@_';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $password;
}

function _text($arr, $field, $otherField)
{
    static $map = ['add' => '添加', 'remove' => '删除', 'view' => '查看', 'edit' => '修改'];
    if (empty($arr) || !array_key_exists($field, $arr)) {
        if (!empty($map[$otherField])) {
            return $map[$otherField];
        }
        return '';
    }
    return $arr[$field];
}

$GLOBALS['v'] = 0.03611211;
function _js($paths)
{
    $paths = explode(',', $paths);
    $tags = [];
    foreach ($paths as $path) {
        $tags[] = '<script src="/' . $path . (strpos($path, '?') > 0 ? '&' : '?') . '_v=' . $GLOBALS['v'] . '"></script>';
    }
    return join("\r\n", $tags);
}

function _css($paths)
{
    $paths = explode(',', $paths);
    $tags = [];
    foreach ($paths as $path) {
        //<link rel="stylesheet" href="/static/css/swiper-3.3.1.min.css">
        $tags[] = '<link rel="stylesheet" href="/' . $path . (strpos($path, '?') > 0 ? '&' : '?') . '_v=' . $GLOBALS['v'] . '">';
    }
    return join("\r\n", $tags);
}

function ccnn_mobile_request()
{
    $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
    $mobile_browser = '0';
    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
        $mobile_browser++;
    if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'application/vnd.wap.xhtml+xml') !== false))
        $mobile_browser++;
    if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
        $mobile_browser++;
    if (isset($_SERVER['HTTP_PROFILE']))
        $mobile_browser++;
    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
    $mobile_agents = array(
        'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
        'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
        'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
        'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
        'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
        'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
        'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
        'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
        'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
    );
    if (in_array($mobile_ua, $mobile_agents))
        $mobile_browser++;
    if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
        $mobile_browser++;
    // Pre-final check to reset everything if the user is on Windows
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
        $mobile_browser = 0;
    // But WP7 is also Windows, with a slightly different characteristic
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
        $mobile_browser++;
    if ($mobile_browser > 0)
        return true;
    else
        return false;
}

function _html($html)
{
    return htmlspecialchars($html);
}

function _op($key, $key2)
{
    return \app\common\util\ValueBag::getOptions($key, $key2);
}

function _img_up($name, $img, $size = '250x130', $title = '')
{
    list($w, $h) = explode('x', $size);
    return '<img name="' . $name . '" src="' . _img_url($size, $img)
        . '" onerror="this.scr=\'' . _img_url($size) . '\'" alt="' . $title . '"
                                     style="height: ' . $h . 'px;width:' . $w . 'px;">';
}

function _img($img, $size = '250x130', $title = '')
{
    list($w, $h) = explode('x', $size);
    if (empty($h)) {
        $h = '100';
    }
    return '<img onclick="showBigImage(this,event)" src="' . _img_url($size, $img)
        . '" onerror="this.scr=\'' . _img_url($size) . '\'" alt="' . $title . '"
                                     style="height: ' . $h . 'px;width:' . $w . 'px;">';
}


function formatTime($date)
{
    $timer = strtotime($date);
    $diff = $_SERVER['REQUEST_TIME'] - $timer;
    $day = floor($diff / 86400);
    $free = $diff % 86400;
    if ($day > 0) {
        return $day . "天前";
    } else {
        if ($free > 0) {
            $hour = floor($free / 3600);
            $free = $free % 3600;
            if ($hour > 0) {
                return $hour . "小时前";
            } else {
                if ($free > 0) {
                    $min = floor($free / 60);
                    $free = $free % 60;
                    if ($min > 0) {
                        return $min . "分钟前";
                    } else {
                        if ($free > 0) {
                            return $free . "秒前";
                        } else {
                            return '刚刚';
                        }
                    }
                } else {
                    return '刚刚';
                }
            }
        } else {
            return '刚刚';
        }
    }
}

function _money_format($v)
{
    return number_format($v / 100, 2);
}

function _timeformat3($time)
{
    if (!empty($time)) {
        $time = strtotime($time);
        return date('m月d H:i', $time);
    }
    return $time;
}